import { AfterViewInit, Component, Input } from '@angular/core';

import { Chart } from '@antv/g2';

import { WidgetConfig } from '../widget-default-setting';

@Component({
  selector: 'app-chart-widget',
  standalone: true,
  imports: [],
  templateUrl: './chart-widget.component.html',
  styleUrl: './chart-widget.component.less'
})
export class ChartWidgetComponent implements AfterViewInit {
  @Input() widget!: WidgetConfig;
  ngAfterViewInit(): void {
    this.createChartByConfig();
  }
  defaultData = [
    { type: '1月', value: 769 },
    { type: '2月', value: 769 },
    { type: '3月', value: 861 },
    { type: '4月', value: 442 },
    { type: '5月', value: 555 },
    { type: '6月', value: 439 },
    { type: '7月', value: 590 },
    { type: '8月', value: 434 },
    { type: '9月', value: 843 },
    { type: '10月', value: 840 },
    { type: '11月', value: 769 },
    { type: '12月', value: 769 }
  ];

  createChartByConfig(): void {
    const chart = new Chart({
      container: 'chart-widget',
      autoFit: true,
      height: 295,
      padding: [40, 40, 32, 72]
    });

    chart.data(this.widget['chartData'] ?? this.defaultData);
    chart.scale('value', {
      nice: true
    });
    chart.axis('type', {
      tickLine: null
    });

    chart.axis('value', {
      label: {
        formatter: val => {
          return +val;
        }
      }
    });

    chart.tooltip({
      showMarkers: false
    });
    chart.interaction('element-active');

    chart.legend(false);
    chart
      .interval()
      .position('type*value')
      .color('type', val => {
        if (val === '10-30分' || val === '30+分') {
          return '#ff4d4f';
        }
        return '#2194ff';
      })
      .label('value', {
        offset: 10
      });
    chart.render();
  }
}
